import zipfile
from pathlib import Path

import allure
import pysnooper
from tools.ERP导入 import 揽收预警上传
from tools.page import page_get
from tools.合并excel import 合并excel


@pysnooper.snoop()
def 聚水潭导出(date, date_hour):
    page = page_get()
    page('text=数据').click(by_js=True)
    page('text=物流实时预警').click()
    page.wait(5)
    page('text=揽收快超时').click()
    page.wait(8)
    page.set.download_path(f'C:/揽收预警/{date}')
    page.set.download_file_name(f'揽收预警{date_hour}.xlsx')
    page('text=导 出').click(by_js=True)
    page.wait(10)
    if page.eles('.ant-notification ant-notification-bottomRight'):
        tr = page('.ant-notification ant-notification-bottomRight').ele('.art-table-row first even')
        下载button = tr('text=下 载', timeout=300)
        下载button.click()
    page.wait.download_begin()
    page.wait.downloads_done(60)
    if Path(f'C:/揽收预警/{date}/揽收预警{date_hour}.xlsx').exists():
        揽收预警上传(f'C:/揽收预警/{date}/揽收预警{date_hour}.xlsx', date_hour)
    else:
        with zipfile.ZipFile(f'C:/揽收预警/{date}/揽收预警{date_hour}.xlsx.zip', 'r') as zip_ref:
            zip_ref.extractall(f'C:/揽收预警/{date}')
        page.wait(3)
        files = Path(f'C:/揽收预警/{date}').glob('订单物流预警明细*.xlsx')
        合并excel(files, f'C:/揽收预警/{date}/揽收预警{date_hour}.xlsx')
        揽收预警上传(f'C:/揽收预警/{date}/揽收预警{date_hour}.xlsx', date_hour)
        Path(f'C:/揽收预警/{date}/揽收预警{date_hour}.xlsx.zip').unlink()
        files = Path(f'C:/揽收预警/{date}').glob('订单物流预警明细*.xlsx')
        for file in files:
            file.unlink()
